package com.cqcis.uip.platform.launcher;

import java.util.Dictionary;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedServiceFactory;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.util.tracker.ServiceTracker;

public class BundleAutoDeploy implements BundleActivator, ManagedServiceFactory {
	static ServiceTracker paTracker;
	static ServiceTracker cmTracker;
		
	private BundleContext context;
	private Map<String, Object> watchers = new HashMap<String, Object>();

	public void start(BundleContext context) throws Exception {
		this.context = context;
		Properties props = new Properties();
		props.put(Constants.SERVICE_PID, getName());
		context.registerService(ManagedServiceFactory.class.getName(), this, props);
				
		paTracker = new ServiceTracker(context, PackageAdmin.class.getName(), null);
		paTracker.open();
		cmTracker = new ServiceTracker(context, ConfigurationAdmin.class.getName(), null);
		cmTracker.open();
		
		// Created the initial configuration
		Properties ht = new Properties();
		set(ht, DirectoryWatcher.LAUNCHER_POLL_KEY);
		set(ht, DirectoryWatcher.LAUNCHER_DIRS_KEY);
		updated("uip-launcher", ht);
	}

	public void stop(BundleContext context) throws Exception {
		for (Iterator<Object> w = watchers.values().iterator(); w.hasNext();) {
			try {
				DirectoryWatcher dir = (DirectoryWatcher) w.next();
				w.remove();
				dir.close();
			} catch (Exception e) {
				// Ignore
			}
		}

		cmTracker.close();
		paTracker.close();
	}

	public void deleted(String pid) {
		DirectoryWatcher watcher = (DirectoryWatcher) watchers.remove(pid);
		if (watcher != null)
			watcher.close();
	}

	public String getName() {
		return "uip.launcher.BundleAutoDeploy";
	}

	private void set(Properties ht, String key) {
		Object o = context.getProperty(key);
		if (o == null)
			return;
		ht.put(key, o);
	}

	@SuppressWarnings("unchecked")
	public void updated(String pid, Dictionary properties) throws ConfigurationException {
		deleted(pid);
		DirectoryWatcher watcher = new DirectoryWatcher(properties, context);
		watchers.put(pid, properties);
		watcher.start();
	}
}
